package com.winning.ywypt.util;



import com.alibaba.fastjson.JSON;
import com.winning.ywypt.Entity.ResponseEntity;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;


import java.io.IOException;

/**
 * @ClassName: ResponseProcessHandler
 * @Author: sujun@winning.com.cn
 * @Desc: 响应处理
 * @Date: 2018-12-19 15:49
 **/

public class ResponseProcessHandler  implements ResponseHandler<String>{

    private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException{
        ResponseEntity responseEntity = processResponse(response);

        String code = (String)responseEntity.getCode();

        if (code != "200") {
            throw new IOException("访问失败");
        }
        String data = (String)responseEntity.getData();
        return data;
    }


    private ResponseEntity processResponse(HttpResponse response) throws IOException{
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            String resultStr = EntityUtils.toString(entity);
            ResponseEntity responseEntity = JSON.parseObject(resultStr,  ResponseEntity.class);
            return responseEntity;
        }

            throw new IOException("网络错误 【" + statusLine.getStatusCode() + "】" );
    }

}
